import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://apifoxmock.com/m1/4840030-4495188-default', // 设置根地址
  timeout: 5000 // 设置超时时间为5秒
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    return Promise.reject(error);
  }
);

// 暴露 rq 方法
export const rq = async (url: string, method: string, data?: any) => {
  try {
    const response = await instance({
      url,
      method,
      data: method.toLowerCase() !== 'get' ? data : null,
      params: method.toLowerCase() === 'get' ? data : null
    });
    return response.data;
  } catch (error) {
    console.error('请求错误:', error);
    throw error;
  }
};
